package com.ruoyi.applet.service.impl;

import com.github.pagehelper.PageInfo;
import com.ruoyi.applet.OutDTO.UserConvertDTO;
import com.ruoyi.applet.OutDTO.UserRankDTO;
import com.ruoyi.applet.domain.*;
import com.ruoyi.applet.mapper.*;
import com.ruoyi.applet.service.IWechatUserService;
import com.brisk.common.core.domain.AjaxResult;
import com.brisk.common.core.page.PageDomain;
import com.brisk.common.core.page.TableSupport;
import com.brisk.common.core.redis.RedisCache;
import com.brisk.common.utils.DateUtils;
import com.brisk.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * weChatUserService业务层处理
 *
 * @author PengFei
 * @date 2022-05-31
 */
@Service
public class WechatUserServiceImpl implements IWechatUserService {
    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Autowired
    private AppletTeamMapper appletTeamMapper;

    @Autowired
    private AppletWalkRowMapper appletWalkRowMapper;

    @Autowired
    private AppletSiteMapper appletSiteMapper;

    @Autowired
    private AppletExamUserMapper appletExamUserMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AppletImgMapper appletImgMapper;


    /**
     * 查询weChatUser
     *
     * @param userId weChatUser主键
     * @return weChatUser
     */
    @Override
    public WechatUser selectWechatUserByUserId(Long userId) {
        return wechatUserMapper.selectWechatUserByUserId(userId);
    }

    /**
     * 查询weChatUser列表
     *
     * @param wechatUser weChatUser
     * @return weChatUser
     */
    @Override
    public List<WechatUser> selectWechatUserList(WechatUser wechatUser) {
        return wechatUserMapper.selectWechatUserList(wechatUser);
    }

    @Override
    public List<WechatUser> selectWechatRankList(WechatUser wechatUser) {
        return wechatUserMapper.getPeopleRankingList(wechatUser);
    }

    /**
     * 新增weChatUser
     *
     * @param wechatUser weChatUser
     * @return 结果
     */
    @Override
    public int insertWechatUser(WechatUser wechatUser) {
        wechatUser.setCreateTime(DateUtils.getNowDate());
        return wechatUserMapper.insertWechatUser(wechatUser);
    }

    /**
     * 修改weChatUser
     *
     * @param wechatUser weChatUser
     * @return 结果
     */
    @Override
    public int updateWechatUser(WechatUser wechatUser) {
        wechatUser.setUpdateTime(DateUtils.getNowDate());
        return wechatUserMapper.updateWechatUser(wechatUser);
    }

    /**
     * 批量删除weChatUser
     *
     * @param userIds 需要删除的weChatUser主键
     * @return 结果
     */
    @Override
    public int deleteWechatUserByUserIds(Long[] userIds) {
        return wechatUserMapper.deleteWechatUserByUserIds(userIds);
    }

    /**
     * 删除weChatUser信息
     *
     * @param userId weChatUser主键
     * @return 结果
     */
    @Override
    public int deleteWechatUserByUserId(Long userId) {
        return wechatUserMapper.deleteWechatUserByUserId(userId);
    }

    @Override
    public WechatUser wxLogin(String openid) {
        WechatUser wechatUser = wechatUserMapper.selectWechatUserByOpenid(openid);
        int res;
        if (ObjectUtils.isEmpty(wechatUser)) { // 第一次授权
            WechatUser newUser = new WechatUser();
            newUser.setOpenid(openid);
            newUser.setUserNickname("微信用户");
            newUser.setUserName("微信用户");
            newUser.setUserImg("https://briskwalking.oss-cn-chengdu.aliyuncs.com/2022/06/02/default_brisk_20220602002101A003.png");
            newUser.setLastLoginTime(DateUtils.getNowDate());
            newUser.setCreateTime(DateUtils.getNowDate());
            res = wechatUserMapper.insertWechatUser(newUser);
        } else {  // 有记录就更新登录时间
            WechatUser update = new WechatUser();
            update.setLastLoginTime(DateUtils.getNowDate());
            update.setOpenid(openid);
            res = wechatUserMapper.updateWechatUserByOpenid(update);
        }
        wechatUser = wechatUserMapper.selectWechatUserByOpenid(openid);
        return wechatUser;
    }


    @Override
    public AjaxResult updateWxData(String nickName, String avatarUrl, Long userId) {
        WechatUser wechatUser = wechatUserMapper.selectWechatUserByUserId(userId);
        if (ObjectUtils.isEmpty(wechatUser)) return AjaxResult.error("获取用户信息失败！");
        wechatUser.setUpdateTime(DateUtils.getNowDate());
        wechatUser.setUpdateBy("小程序用户：" + userId);
        if (!StringUtils.isEmpty(nickName)) wechatUser.setUserNickname(nickName);
        if (!StringUtils.isEmpty(avatarUrl)) wechatUser.setUserImg(avatarUrl);
        int res = wechatUserMapper.updateWechatUser(wechatUser);
        return res > 0 ? AjaxResult.success("同步成功！", wechatUser) : AjaxResult.error("同步成功！");
    }

    @Override
    @Transactional
    public AjaxResult userRegister(WechatUser wechatUser) {
        WechatUser select = wechatUserMapper.selectWechatUserByUserId(wechatUser.getUserId());
        if (ObjectUtils.isEmpty(select)) return AjaxResult.error("获取用户信息失败！");
        AppletTeam appletTeam = appletTeamMapper.selectAppletTeamByTeamId(wechatUser.getTeamId());
        if (ObjectUtils.isEmpty(appletTeam)) return AjaxResult.error("获取队伍信息失败");
        wechatUser.setRegisterTime(DateUtils.getNowDate());
        wechatUser.setTeamName(appletTeam.getTeamName());
        wechatUser.setUpdateTime(DateUtils.getNowDate());
        wechatUser.setUpdateBy("微信用户:" + wechatUser.getUserId());
        int res = wechatUserMapper.updateWechatUser(wechatUser);
        if (res > 0) { //更新队伍的人数
            AppletTeam update = new AppletTeam();
            update.setTeamId(wechatUser.getTeamId());
            update.setPeopleSum(1);
            int res2 = appletTeamMapper.updateAppletTeamSum(update);
            return res2 > 0 ? AjaxResult.success("注册成功！") : AjaxResult.error("注册失败！");
        }
        return AjaxResult.error("注册失败！");
    }

    @Override
    public List<UserRankDTO> getPeopleRankingList(List<WechatUser> rankList) {
        List<UserRankDTO> userRankDTOList = new ArrayList<>();
        int pageNum = getPageNum(rankList);
        for (int i = 0; i < rankList.size(); i++) {
            WechatUser temp = rankList.get(i);
            UserRankDTO userRankDTO = new UserRankDTO();
            userRankDTO.setUnit("里");
            userRankDTO.setMileage(temp.getMileage());
            getUserRankDTO(userRankDTOList, pageNum, i, temp, userRankDTO);
        }
        return userRankDTOList;
    }

    @Override
    public List<UserRankDTO> getTodayRankingList(List<AppletWalkRow> walkRowList) {
        List<UserRankDTO> userRankDTOList = new ArrayList<>();
        int pageNum = getPageNum(walkRowList);
        for (int i = 0; i < walkRowList.size(); i++) {
            AppletWalkRow row = walkRowList.get(i);
            WechatUser temp = wechatUserMapper.selectWechatUserByUserId(row.getUserId());
            if (!ObjectUtils.isEmpty(temp)) {
                UserRankDTO userRankDTO = new UserRankDTO();
                userRankDTO.setUnit("步");
                userRankDTO.setStepNumber(row.getNowWalk());
                getUserRankDTO(userRankDTOList, pageNum, i, temp, userRankDTO);
            }
        }
        return userRankDTOList;
    }

    @Override
    public AjaxResult getUserConvertInfo(Long userId) {
        WechatUser wechatUser = wechatUserMapper.selectWechatUserByUserId(userId);
        if (ObjectUtils.isEmpty(wechatUser)) return AjaxResult.error("获取用户信息失败");
        UserConvertDTO convertDTO = new UserConvertDTO();
        //组装用户基本信息  查找用户信息就能获取的
        convertDTO.setConvert("20步=1里");
        convertDTO.setUserId(userId);
        convertDTO.setUserName(wechatUser.getUserName());
        convertDTO.setAvatarUrl(wechatUser.getUserImg());
        convertDTO.setNickName(wechatUser.getUserNickname());
        convertDTO.setMileageSum(wechatUser.getMileage());
        convertDTO.setDaySum(wechatUser.getDaySum());
        //组装用胡今日兑换信息
        AppletWalkRow appletWalkRow = appletWalkRowMapper.selectTodayAppletWalkRowByRowId(userId);
        if (ObjectUtils.isEmpty(appletWalkRow)) {
            appletWalkRow = new AppletWalkRow();
            appletWalkRow.setNowWalk(1);
            appletWalkRow.setAgoWalk(0);
        }
        convertDTO.setTodayConvertSum(appletWalkRow.getAgoWalk());
        int canConvertSum = appletWalkRow.getNowWalk() - appletWalkRow.getAgoWalk();
        convertDTO.setCanConvertSum(canConvertSum > 0 ? canConvertSum : 1);
        //查询用户到达的站点 用户累计里程 小于等于 站点解锁里程
        AppletSite userNowSite = appletSiteMapper.getUserSite(wechatUser.getMileage());
        if (ObjectUtils.isEmpty(userNowSite)) { //判断是否起点
            convertDTO.setSiteId(null);
            convertDTO.setSiteName("您还在起点");
            convertDTO.setSiteBackgroundImg(null);
            convertDTO.setStart(true);
            convertDTO.setAllowGO(false);
        } else {
            convertDTO.setSiteId(userNowSite.getSiteId());
            convertDTO.setSiteName(userNowSite.getSiteName());
            convertDTO.setSiteBackgroundImg(userNowSite.getConvertImg());
            convertDTO.setStart(false);
            convertDTO.setAllowGO(true);
        }
        //获取用户下一个站点的信息
        AppletSite userNextSite = appletSiteMapper.getUserNextSite(wechatUser.getMileage());
        if (ObjectUtils.isEmpty(userNextSite)) {//到达终点
            convertDTO.setNextSiteName(userNowSite.getSiteName());
            convertDTO.setNextSiteMileage(new BigDecimal(0));
            convertDTO.setFinish(true);
        } else {
            convertDTO.setNextSiteName(userNextSite.getSiteName());
            convertDTO.setNextSiteMileage(userNextSite.getSiteLockMileage().subtract(wechatUser.getMileage()));
            convertDTO.setFinish(false);
        }

        //获取用户的排名
        Integer rank = wechatUserMapper.getUserRankInRankList(userId);
        convertDTO.setRank(rank == null ? 0 : rank);
        return AjaxResult.success("获取信息成功！", convertDTO);
    }

    @Override
    public int getUserRankInRankList(Long userId) {
        Integer rank = wechatUserMapper.getUserRankInRankList(userId);
        return rank == null ? 0 : rank;
    }

    @Override
    public AjaxResult getUserScoreRankList(Integer pageNum, Integer pageSize) {
        AjaxResult ajaxResult = AjaxResult.success();
        List<WechatUser> wechatUserList = wechatUserMapper.selectWechatUserList(new WechatUser());
        List<UserRankDTO> userRankDTOList = new ArrayList<>();
        if (wechatUserList.size() == 0) {
            ajaxResult.put("total", 0);
            ajaxResult.put("rows", userRankDTOList);
        }
        for (WechatUser wechatUser : wechatUserList) {
            UserRankDTO userRankDTO = new UserRankDTO();
            //统计用户解锁了几个点位
            Integer lockSiteNum = appletSiteMapper.countUserLockSiteNum(wechatUser.getMileage());
            lockSiteNum = lockSiteNum == null ? 0 : lockSiteNum;
            //统计用户的答题正确数量
            Integer topicTrueSum = appletExamUserMapper.getUserAllTrueSum(wechatUser.getUserId());
            topicTrueSum = topicTrueSum == null ? 0 : topicTrueSum;
            long score = lockSiteNum * 500 + topicTrueSum * 50;
            userRankDTO.setUserId(wechatUser.getUserId());
            userRankDTO.setUserName(wechatUser.getUserName() == null ? wechatUser.getUserNickname() : wechatUser.getUserName());
            userRankDTO.setAvatarUrl(wechatUser.getUserImg());
            userRankDTO.setScore(score);
            userRankDTO.setUnit("分");
            userRankDTO.setNickName(wechatUser.getUserNickname());
            userRankDTOList.add(userRankDTO);
        }
        userRankDTOList = userRankDTOList.stream().sorted((a, b) -> b.getScore().compareTo(a.getScore())).collect(Collectors.toList());

        //设置排名
        for (int i = 0; i < userRankDTOList.size(); i++) {
            userRankDTOList.get(i).setRank(i + 1);
        }
        redisCache.setCacheList("user_score_rank_list", userRankDTOList);
        redisCache.expire("user_score_rank_list", 60 * 20);
        ajaxResult.put("total", userRankDTOList.size());
        //确定返回的数据
        if (null != pageNum && null != pageSize) {
            int start = (pageNum - 1) * pageSize;
            int end = (start + pageSize) < userRankDTOList.size() ? (start + 10) : userRankDTOList.size();
            List<UserRankDTO> returnList = new ArrayList<>();
            for (int i = start; i < end; i++) {
                returnList.add(userRankDTOList.get(i));
                ajaxResult.put("rows", returnList);
            }
        } else {
            ajaxResult.put("rows", userRankDTOList);
        }
        return ajaxResult;
    }

    @Override
    public AjaxResult getUserCertificate(Long userId) {
        //重新用户接受了几个点位
        WechatUser wechatUser =wechatUserMapper.selectWechatUserByUserId(userId);
        Integer userLockSiteNum = appletSiteMapper.countUserLockSiteNum(wechatUser.getMileage());
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("isGet",false);
        if (userLockSiteNum == null || userLockSiteNum==0) return ajaxResult;
        //查询总的点位
        int siteSum = appletSiteMapper.getSiteNumber();
        if (userLockSiteNum >= siteSum){
            //查询用户勋证书
            AppletImg appletImg =  appletImgMapper.selectAppletImgByImgId(40L);
            ajaxResult.put("isGet",true);
            ajaxResult.put("data",appletImg.getImgUrl());
            return ajaxResult;
        }
        return ajaxResult;
    }

    /**
     * 组合数据
     *
     * @author PengFei Deng
     * @date 2022/6/2 13:05
     */
    private void getUserRankDTO(List<UserRankDTO> userRankDTOList, int pageNum, int i, WechatUser temp, UserRankDTO userRankDTO) {
        userRankDTO.setUserId(temp.getUserId());
        userRankDTO.setUserName(temp.getUserName());
        userRankDTO.setAvatarUrl(temp.getUserImg());
        userRankDTO.setDaySum(temp.getDaySum());
        userRankDTO.setNickName(temp.getUserNickname());
        if (pageNum > 1) {
            userRankDTO.setRank((pageNum - 1) * 10 + i + 1);
        } else {
            userRankDTO.setRank(i + 1);
        }
        userRankDTOList.add(userRankDTO);
    }

    /**
     * 获取页码 用户计算排名
     *
     * @return int
     * @author PengFei Deng
     * @date 2022/6/2 3:40
     */
    private int getPageNum(List<?> list) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum() == null ? 1 : pageDomain.getPageNum();  //获取当前页数
        int pageSize = pageDomain.getPageSize();
        long total = new PageInfo<>(list).getTotal();
        int maxPageNum = (int) (total / pageSize + 1);
        pageNum = Math.min(pageNum, maxPageNum);
        return pageNum;
    }


}
